package com.fzrskj.cloud.free.user.utils;

import com.alibaba.fastjson.JSONObject;
import com.fzrskj.cloud.free.core.enums.PriceTypeEnum;
import com.fzrskj.cloud.free.core.enums.ProductTypeEnum;
import com.fzrskj.cloud.free.core.enums.PromotionEnum;
import com.fzrskj.cloud.free.core.enums.diy.DiyNoticeTemplateEnum;
import com.fzrskj.cloud.free.core.enums.diy.DiyProductStatusEnum;
import com.fzrskj.cloud.free.core.tool.CDateTimeTool;
import com.fzrskj.cloud.free.core.utils.CloudContextUtils;
import com.fzrskj.cloud.free.core.utils.DoubleUtil;
import com.fzrskj.cloud.free.dic.utils.DicPriceVHostUtils;
import com.fzrskj.cloud.free.miniservice.utils.DiyProductSyncUtils;
import com.fzrskj.cloud.free.sys.bean.SysProductView;
import com.fzrskj.cloud.free.sys.bean.SysPromotion;
import com.fzrskj.cloud.free.sys.utils.SendMailUtils;
import com.fzrskj.cloud.free.sys.utils.SendSMSUtils;
import com.fzrskj.cloud.free.sys.utils.SysPriceUpdateRecordUtils;
import com.fzrskj.cloud.free.sys.utils.SysProductUtils;
import com.fzrskj.cloud.free.user.bean.UserDiyViewBean;
import com.fzrskj.cloud.free.user.bean.UserAccountView;
import com.fzrskj.cloud.free.user.bean.UserDiyBean;
import com.fzrskj.cloud.free.user.bean.UserOrder;
import com.fzrskj.cloud.free.user.dao.UserDiyDao;
import com.winiis.component.common.utils.bean.ClassUtils;
import ms.core.consts.SysErr;
import ms.core.db.ConnectionContext;
import ms.core.object.CObject;
import ms.core.tool.DateTimeTool;
import ms.core.tool.StrTool;
import org.apache.commons.collections.map.HashedMap;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class UserDiyUtils extends CObject{
	//private declarations
	private UserDiyDao dao=null;

	//constructor function to initialize database access object
	public UserDiyUtils(){ dao=new UserDiyDao(); }

	//to free resource
	@Override
	public void dispose(){
		if (dao!=null) {
			dao.dispose();
		}
		dao = null;
		super.dispose();
	}

	//new record by map
	public int newUserDiy(Map<String, Object> values){
		int ret = dao.newUserDiy(values);
		this.setErrCode(dao.getErrCode());
		return ret;
	}

	public Integer getLastId() {
		return this.dao.getLastId();
	}

	//delete record by id
	public int delUserDiy(int id){
		int ret = dao.delUserDiy(id);
		this.setErrCode(dao.getErrCode());
		if (ret==0) {
			this.setErrCode(SysErr.SYS_DATA_NOT_FOUND);
		}
		return ret;
	}

	//modify record by map
	public int modUserDiy(Map<String,Object> values, Map<String,Object> cdt){
		Boolean uptRenewPrice = false;
		String remark = "";
		if (values.containsKey("renewMonthPrice")){
			uptRenewPrice = true;
			remark += "修改按月续费价格为【"+values.get("renewMonthPrice")+"】,";
			//values.put("renewMonthPrice", param.get("renewMonthPrice"));
		}
		if (values.containsKey("renewYearPrice")){
			uptRenewPrice = true;
			remark += "修改按年续费价格为【"+values.get("renewYearPrice")+"】";
			//values.put("renewYearPrice", param.get("renewYearPrice"));
		}
		int ret = dao.modUserDiy(values, cdt);

		if(uptRenewPrice){
			SysPriceUpdateRecordUtils.addServicePriceUpdateRecord(CloudContextUtils.getSession().getUname(), CloudContextUtils.getSession().getUID(), remark, "");
		}
		this.setErrCode(dao.getErrCode());
		if (ret==0) {
			this.setErrCode(SysErr.SYS_DATA_NOT_FOUND);
		}
		return ret;
	}

	public int modTrandferAccount(Map<String,Object> values, Map<String,Object> cdt){
		int ret = dao.modTransferUserDiy(values, cdt);
		this.setErrCode(dao.getErrCode());
		if (ret==0) {
			this.setErrCode(SysErr.SYS_DATA_NOT_FOUND);
		}
		return ret;
	}

	/**
	 * 获取虚机自定次续费价格实际
	 * @param id
	 * @return
	 * add by hl831 2019.11.127
	 */
	public List<SysPromotion> getDiyHostRenewPriceTime(int id){
		List<SysPromotion> promotionList = new ArrayList<>();
		UserDiyBean diy = dao.qryUserDiy(id);

		do {
			if (null == diy){
				break;
			}
			diy = setDefRenewPirce(diy);
			if (diy.getRenewMonthPrice() > 0 || diy.getRenewYearPrice() > 0 ){
				SysPromotion sp;
				if (diy.getRenewMonthPrice() > 0){
					sp = new SysPromotion();
					sp.setChargeId(2);
					sp.setApplyType(PriceTypeEnum.MONTH.getFlag());
					sp.setApplyTime(1);
					sp.setSaleType(PromotionEnum.NONE.getValue());
					promotionList.add(sp);
				}
				if (diy.getRenewYearPrice()> 0){
					sp = new SysPromotion();
					sp.setChargeId(2);
					sp.setApplyType(PriceTypeEnum.YEAR.getFlag());
					sp.setApplyTime(1);
					sp.setSaleType(PromotionEnum.NONE.getValue());
					promotionList.add(sp);
				}

			}
		} while (false);
		return promotionList;
	}

    /**
     * 续费价格空值处理
     * @param ud
     * @return
     * add by hl831 2019.11.28
     */
    public static UserDiyBean setDefRenewPirce(UserDiyBean ud){
        ud.setRenewMonthPrice(ud.getRenewMonthPrice() == null ? 0 : ud.getRenewMonthPrice());
        ud.setRenewYearPrice(ud.getRenewYearPrice() == null ? 0 : ud.getRenewYearPrice());
        return ud;
    }

    /**
     * 判断有没有设置续费价格
     * @param usv
     * @return
     * add by hl831 2019.11.28
     */
    public static Boolean isDivRenewPirce(UserDiyBean usv){
        usv = setDefRenewPirce(usv);
        Boolean isDivRenew = false;
        if (usv.getRenewMonthPrice() > 0 || usv.getRenewYearPrice() > 0){
            isDivRenew = true;
        }

        return isDivRenew;
    }

    /**
     * 根据续费类型获取价格
     * @param priceType
     * @param usv
     * @return
     * add by hl831 2019.11.28
     */
    public static Integer getDivRenewPirce(String priceType, UserDiyBean usv){
        usv = setDefRenewPirce(usv);
        Integer renewPrice = 0;
        if (PriceTypeEnum.MONTH.equals(priceType)){
            renewPrice = usv.getRenewMonthPrice();
        }

        if (PriceTypeEnum.YEAR.equals(priceType)){
            renewPrice = usv.getRenewYearPrice();
        }
        return renewPrice;
    }

	//query record by id
	public UserDiyBean queryUserDiy(int id){
	    UserDiyBean ret = dao.queryUserDiy(id);
		String err = dao.getErrCode();
		this.setErrCode(err);
		if (err.equals(SysErr.CODE_SUCCESS) && ret==null) {
			this.setErrCode(SysErr.SYS_DATA_NOT_FOUND);
		}
		return ret;
	}

	public UserDiyBean qryUserDiy(int id){
		UserDiyBean ret = dao.qryUserDiy(id);
		String err = dao.getErrCode();
		this.setErrCode(err);
		if (err.equals(SysErr.CODE_SUCCESS) && ret==null) {
			this.setErrCode(SysErr.SYS_DATA_NOT_FOUND);
		}
		return ret;
	}

	//query record count by cdt
	public int queryUserDiy(Map<String,Object> cdt){
		int ret = dao.queryUserDiy(cdt);
		this.setErrCode(dao.getErrCode());
		return ret;
	}

	//query record list by cdt
	public List<UserDiyBean> queryUserDiy(Map<String,Object> cdt,String orderby, int page,int pagesize){
		List<UserDiyBean> rets = dao.queryUserDiy(cdt,orderby,page,pagesize);
		String err = dao.getErrCode();
		this.setErrCode(err);
		if (err.equals(SysErr.CODE_SUCCESS) && (rets==null || rets.size()==0)){
			this.setErrCode(SysErr.SYS_DATA_NOT_FOUND);
		}
		return rets;
	}

	/**
	 * 用户获取业务列表总数.
	 * @param cdt
	 * @return
	 */
	public Integer userQuery(Map<String, Object> cdt) {
		Integer total = this.dao.userQuery(cdt);
		String err = this.dao.getErrCode();
		this.setErrCode(err);
		return total;
	}

	/**
	 * 用户获取业务列表.
	 * @param cdt
	 * @param orderBy
	 * @param page
	 * @param pageSize
	 * @return
	 */
	public List<UserDiyViewBean> userQuery(Map<String, Object> cdt, String orderBy, Integer page, Integer pageSize) {
		List<UserDiyViewBean> viewBeans = this.dao.userQuery(cdt, orderBy, page, pageSize);
		String err = this.dao.getErrCode();
		this.setErrCode(err);
		if (null != viewBeans) {
			viewBeans.forEach(item->{
				item.setStatusName(DiyProductStatusEnum.getName(item.getStatus()));
			});
		}
		return viewBeans;
	}

	/**
	 * 管理员获取业务列表总数.
	 * @param cdt
	 * @return
	 */
	public Integer adminQuery(Map<String, Object> cdt) {
		Integer total = this.dao.adminQuery(cdt);
		String err = this.dao.getErrCode();
		this.setErrCode(err);
		return total;
	}

	/**
	 * 管理员获取业务列表.
	 * @param cdt
	 * @param orderBy
	 * @param page
	 * @param pageSize
	 * @return
	 */
	public List<UserDiyViewBean> adminQuery(Map<String, Object> cdt, String orderBy, Integer page, Integer pageSize) {
		List<UserDiyViewBean> viewBeans = this.dao.adminQuery(cdt, orderBy, page, pageSize);
		String err = this.dao.getErrCode();
		this.setErrCode(err);
		if (null != viewBeans) {
			viewBeans.forEach(item->{
				item.setStatusName(DiyProductStatusEnum.getName(item.getStatus()));
			});
		}
		return viewBeans;
	}

	/**
	 * 开通产品.
	 * @param orderView
	 * @return
	 */
	public String createInstance(UserOrder orderView) {
		JSONObject result = new JSONObject();
		result.put("productClass", ProductTypeEnum.DIY.getTag());
		SysProductUtils sysProductUtils = new SysProductUtils();
		SysProductView productView = sysProductUtils.querySysProduct(ProductTypeEnum.DIY.getTag(), orderView.getProductCode());
		if (null == productView) {
			result.put("code", "-1");
			result.put("message", "开通失败：产品不存在");
			return JSONObject.toJSONString(result);
		}

		UserDiyBean diyBean = new UserDiyBean();
		diyBean.setApplyTime(Integer.valueOf(orderView.getApplyTime()).longValue());
		Date endDate = CDateTimeTool.dateAdd(orderView.getPriceType(), orderView.getApplyTime());
		endDate = CDateTimeTool.dateAdd(endDate, 0, 0,
				DicPriceVHostUtils.getPromotionDays(orderView.getProductCode(), 1, orderView.getApplyTime(), orderView.getPriceType()));
		diyBean.setEndTime(endDate);
		diyBean.setOrderId(orderView.getOrderId());
		diyBean.setPrice(orderView.getPayAmount());
		diyBean.setPriceType(orderView.getPriceType());
		diyBean.setProductCode(orderView.getProductCode());
		diyBean.setSubClass(productView.getSubClass());
		diyBean.setStartTime(new Date());
		diyBean.setStatus(DiyProductStatusEnum.WAIT.getStatus());
		diyBean.setUserId(orderView.getUserId());
		diyBean.setOpenInfo(orderView.getOrderParam());
		diyBean.setInstanceInfo("");
		diyBean.setProductName(productView.getProductName());
		diyBean.setUpdateTime(new Date());
		this.newUserDiy(ClassUtils.beanToMap(diyBean));
		if (!SysErr.CODE_SUCCESS.equals(this.getErrCode())) {
			result.put("code", "-1");
			result.put("message", "开通失败：" + this.getMsg());
			return JSONObject.toJSONString(result);
		}

		//是否通知第三方微服务.
		Integer id = this.getLastId();

		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					JSONObject productParam = JSONObject.parseObject(productView.getProductParam());
					String paramShow = productParam.getString("paramShow");
					if ("diy".equals(paramShow)) {
						String miniServer = productParam.getString("miniServer");
						JSONObject orderParam = JSONObject.parseObject(orderView.getOrderParam());
						JSONObject diyParams = orderParam.getJSONObject("diy_params");
						diyParams.put("business_id", id);
						diyParams.put("user_Id", diyBean.getUserId());
						diyParams.put("startTime", DateTimeTool.dateToDateTimeString(diyBean.getStartTime()));
						diyParams.put("endTime", DateTimeTool.dateToDateTimeString(diyBean.getEndTime()));
						diyParams.put("productName", diyBean.getProductName());
						DiyProductSyncUtils syncUtils = new DiyProductSyncUtils();
						syncUtils.syncOpen(miniServer, diyParams);
					}
				} finally {
					ConnectionContext.closeAllConnection();
				}
			}
		}).start();


		result.put("code", "0");
		result.put("message", "开通成功，稍后客服会将产品信息发送给您");
		return JSONObject.toJSONString(result);
	}

	public String renewInstance(UserOrder userOrder) {
		JSONObject result = new JSONObject();
		result.put("productClass", ProductTypeEnum.DIY.getTag());
		SysProductUtils sysProductUtils = new SysProductUtils();
		SysProductView productView = sysProductUtils.querySysProduct(ProductTypeEnum.DIY.getTag(), userOrder.getProductCode());
		if (null == productView) {
			result.put("code", "-1");
			result.put("message", "开通失败：产品不存在");
			return JSONObject.toJSONString(result);
		}

		JSONObject orderParam = JSONObject.parseObject(userOrder.getOrderParam());
		//获取旧业务信息
		Integer oldId = orderParam.getInteger("id");
		UserDiyBean diyBean = this.queryUserDiy(oldId);
		if (null == diyBean) {
			result.put("code", "-1");
			result.put("message", "开通失败：业务不存在");
			return JSONObject.toJSONString(result);
		}

		diyBean.setPrice(DoubleUtil.add(userOrder.getPayAmount(), diyBean.getPrice()));
		//续期
		Date endDate = CDateTimeTool.dateAdd(diyBean.getEndTime(), userOrder.getPriceType(), userOrder.getApplyTime());
		endDate = CDateTimeTool.dateAdd(endDate, 0, 0,
				DicPriceVHostUtils.getPromotionDays(userOrder.getProductCode(), 2, userOrder.getApplyTime(), userOrder.getPriceType()));
		diyBean.setEndTime(endDate);
		Map<String, Object> where = new HashedMap();
		where.put("id", diyBean.getId());
		this.modUserDiy(ClassUtils.beanToMap(diyBean), where);
		if (!SysErr.CODE_SUCCESS.equals(this.getErrCode())) {
			result.put("code", "-1");
			result.put("message", "续费失败：" + this.getMsg());
			return JSONObject.toJSONString(result);
		}

		//通知第三方
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					JSONObject productParam = JSONObject.parseObject(productView.getProductParam());
					String paramShow = productParam.getString("paramShow");
					if ("diy".equals(paramShow)) {
						String miniServer = productParam.getString("miniServer");
						JSONObject orderParam = JSONObject.parseObject(userOrder.getOrderParam());
						JSONObject diyParams = orderParam.getJSONObject("diy_params");
						diyParams.put("business_id", diyBean.getId());

						DiyProductSyncUtils syncUtils = new DiyProductSyncUtils();
						syncUtils.syncRenew(miniServer, diyParams);
					}
				} finally {
					ConnectionContext.closeAllConnection();
				}
			}
		}).start();

		result.put("code", "0");
		result.put("message", "续费成功");
		return JSONObject.toJSONString(result);
	}

	public String upgradeInstance(UserOrder userOrder) {
		JSONObject result = new JSONObject();
		result.put("productClass", ProductTypeEnum.DIY.getTag());
		SysProductUtils sysProductUtils = new SysProductUtils();
		SysProductView productView = sysProductUtils.querySysProduct(ProductTypeEnum.DIY.getTag(), userOrder.getProductCode());
		if (null == productView) {
			result.put("code", "-1");
			result.put("message", "开通失败：产品不存在");
			return JSONObject.toJSONString(result);
		}

		JSONObject orderParam = JSONObject.parseObject(userOrder.getOrderParam());
		//获取旧业务信息
		Integer oldId = orderParam.getInteger("id");
		UserDiyBean diyBean = this.queryUserDiy(oldId);
		if (null == diyBean) {
			result.put("code", "-1");
			result.put("message", "开通失败：业务不存在");
			return JSONObject.toJSONString(result);
		}

		diyBean.setPrice(DoubleUtil.add(userOrder.getPayAmount(), diyBean.getPrice()));

		//更新开通参数
		JSONObject openInfo = JSONObject.parseObject(diyBean.getOpenInfo());
		JSONObject diyParams = openInfo.getJSONObject("diy_params");
		diyParams.putAll(orderParam.getJSONObject("diy_params"));
		openInfo.put("order_describe", orderParam.get("order_describe"));
		openInfo.put("diy_params", diyParams);

		diyBean.setOpenInfo(JSONObject.toJSONString(diyParams));

		Map<String, Object> where = new HashedMap();
		where.put("id", diyBean.getId());
		this.modUserDiy(ClassUtils.beanToMap(diyBean), where);
		if (!SysErr.CODE_SUCCESS.equals(this.getErrCode())) {
			result.put("code", "-1");
			result.put("message", "升级失败：" + this.getMsg());
			return JSONObject.toJSONString(result);
		}

		//通知第三方
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					JSONObject productParam = JSONObject.parseObject(productView.getProductParam());
					String paramShow = productParam.getString("paramShow");
					if ("diy".equals(paramShow)) {
						String miniServer = productParam.getString("miniServer");
						JSONObject orderParam = JSONObject.parseObject(userOrder.getOrderParam());
						JSONObject diyParams = orderParam.getJSONObject("diy_params");
						diyParams.put("business_id", diyBean.getId());

						DiyProductSyncUtils syncUtils = new DiyProductSyncUtils();
						syncUtils.syncRenew(miniServer, diyParams);
					}
				} finally {
					ConnectionContext.closeAllConnection();
				}
			}
		}).start();

		result.put("code", "0");
		result.put("message", "续费成功");
		return JSONObject.toJSONString(result);
	}

	public List<UserDiyViewBean> queryExpiryDiy(int expiryDays, String subClass) {
		String startTime = CDateTimeTool.getDivDay(new Date(), expiryDays);
		String endTime = CDateTimeTool.getDivDay(new Date(), expiryDays+1);

		List<UserDiyViewBean> rets = this.dao.queryExpiryDiy(startTime, endTime, subClass);
		String err = this.dao.getErrCode();
		this.setErrCode(err);
		if (err.equals(SysErr.CODE_SUCCESS) && (rets==null || rets.size()==0)){
			this.setErrCode(SysErr.SYS_DATA_NOT_FOUND);
		}
		return rets;
	}

	public List<UserDiyViewBean> queryExpiryDiy(String startTime, String endTime, String subClass) {
		List<UserDiyViewBean> rets = this.dao.queryExpiryDiy(startTime, endTime, subClass);
		String err = this.dao.getErrCode();
		this.setErrCode(err);
		if (err.equals(SysErr.CODE_SUCCESS) && (rets==null || rets.size()==0)){
			this.setErrCode(SysErr.SYS_DATA_NOT_FOUND);
		}
		return rets;
	}


	/**
	 *  发送提醒.
	 * @param id
	 * @param alertWay
	 * @return
	 */
	public Boolean sendAlert(Integer id, String alertWay) {

		UserDiyBean	diyBean = this.queryUserDiy(id);
		if (null == diyBean) {
			this.setErrCode(SysErr.SYS_DATA_NOT_FOUND);
			return false;
		}

		UserAccountUtils accountUtils = new UserAccountUtils();
		UserAccountView accountView = accountUtils.queryUserAccountViewByUid(diyBean.getUserId());
		if (null == accountView) {
			this.setErrCode("USER_NOT_FOUND", "用户不存在");
			return false;
		}

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		String endTime = DateTimeTool.dateToDateTimeString(diyBean.getEndTime());

		//邮件提醒
		if (alertWay.indexOf("mail") > -1 && !StrTool.isBlankStr(accountView.getEmail())) {
			JSONObject openInfo = JSONObject.parseObject(diyBean.getOpenInfo());
			String productDetail = openInfo.getString("productDetail");
			StringBuilder productInfo = new StringBuilder("产品名称：").append(diyBean.getProductName());
			if (diyBean.getEndTime().getTime() > System.currentTimeMillis()) {
				productInfo.append("\n将于").append(endTime).append("到期。");
			} else {
				productInfo.append("\n于").append(endTime).append("已到期。");
			}
			productInfo.append("\n产品信息：\n").append(productDetail);
			params.add(new BasicNameValuePair("\\[产品基本信息\\]", productInfo.toString()));
			SendMailUtils mailUtils = new SendMailUtils();
			mailUtils.loadWebsiteParam(params);

			mailUtils.sendMail(DiyNoticeTemplateEnum.MAIL_EXPIRE.getName(), accountView.getEmail(), params);
		}
		//短信提醒
		if (alertWay.indexOf("sms") > -1 && !StrTool.isBlankStr(accountView.getMobile())) {
			params.add(new BasicNameValuePair("\\[到期时间\\]", DateTimeTool.dateToDateTimeString(diyBean.getEndTime())));
			params.add(new BasicNameValuePair("\\[产品名称\\]", diyBean.getProductName()));

			Map<String,Object> map = new HashedMap();
			map.put("userId", diyBean.getUserId());
			map.put("mobile", accountView.getMobile());

			SendSMSUtils smsUtils = new SendSMSUtils();
			smsUtils.loadWebsiteParam(params);
			smsUtils.sendSMS(DiyNoticeTemplateEnum.SMS_EXPIRE.getName(), map, params);
		}
		return true;
	}


	public static void main(String[] args) {
		//AlliyunDomainTask.uptAliyunTaskStatus();

	}
}